<template>
  <el-radio-group v-model.trim="currentValue" v-bind="$attrs" @update:modelValue="handleInputEvent">
    <el-radio
      v-for="item in options"
      :key="item[model.value] ?? item[model.label]"
      :label="
        item[model.value] !== undefined && item[model.value] !== null
          ? item[model.value]
          : item[model.label]
      "
      :disabled="item.disabled"
      :border="item.border"
      :size="item.size"
      :name="item.name"
      v-on="$attrs"
    >
      {{ item[model.label] }}
    </el-radio>
  </el-radio-group>
</template>

<script lang="ts">
import { defineComponent, PropType, computed, ref, watch } from "vue";

interface OptionItem {
  [key: string]: any;
  disabled?: boolean;
  border?: boolean;
  size?: "large" | "default" | "small";
  name?: string;
}

interface ModelConfig {
  label: string;
  value: string;
}

export default defineComponent({
  name: "Radio",
  props: {
    modelValue: {
      type: [String, Number, Boolean] as PropType<string | number | boolean>,
      default: "",
    },
    options: {
      type: Array as PropType<OptionItem[]>,
      default: () => [],
    },
    model: {
      type: Object as PropType<ModelConfig>,
      default: null,
    },
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const currentValue = ref(props.modelValue);

    const model = computed(() => {
      if (props.model) {
        return {
          label: props.model.label,
          value: props.model.value,
        };
      }
      return { label: "label", value: "value" };
    });

    watch(
      () => props.modelValue,
      (val) => {
        currentValue.value = val;
      }
    );

    const handleInputEvent = (value: string | number | boolean | undefined) => {
      // Filter out undefined values if needed
      if (value !== undefined) {
        emit("update:modelValue", value);
      }
    };

    return {
      currentValue,
      model,
      handleInputEvent,
    };
  },
});
</script>

<style lang="scss" scoped>
.el-radio-button__inner,
.el-radio-group {
  width: 100%;
}
</style>
